﻿using System;
using System.Collections.Generic;
//ing System.Linq;
using System.Text;
using System.Management;    //需要引用System.Management.dll
using System.Security.Cryptography;

using System.IO;

namespace AppHelper
{
    /// <summary>
    /// 注册管理器
    /// </summary>
    public class AppLicense
    {
        /// <summary>
        /// 私钥  用于生成注册码  请注释掉
        /// </summary>
        // private const string privateKey = "gDOOuok04NHgreQ6rXXHKHA/wbHSaeWlk0F+qe6sDHBr2E/jIa5rpxhHReKKohObzP6hAKSgoMhON1hoXsznVWUG7PfA/dumVRxo6sgVxMjbw54N/iztZIjx0ALX1cPOng/kyh2Fnv0kRV0E/e6ZifYGDKJBXYWuUrOkhMkuFw4JyoyZtA9BFADbF3zpJEGnKz9oh5kONhIfOt2V8yPNu+4WVukY6jLZS+/jqy0IyBPlw9/yViP+DNBUkLztJOTAFOEINOlfIVEdmC20YyaHo8/fTMH3HbF9kfImmN8DJGGx72Sm2JpM73Rb4yvLYPGz0h9QFiFEn7he1mTZx5A4MTE=";
        /// <summary>
        /// 公钥  用于软件解密注册码 
        /// </summary>
        public string publicKey = "AwEAAcqMmbQPQRQA2xd86SRBpys/aIeZDjYSHzrdlfMjzbvuFlbpGOoy2Uvv46stCMgT5cPf8lYj/gzQVJC87STkwBThCDTpXyFRHZgttGMmh6PP30zB9x2xfZHyJpjfAyRhse9kptiaTO90W+Mry2Dxs9IfUBYhRJ+4XtZk2ceQODEx";


        /// <summary>
        /// 私钥  用于生成注册码
        /// </summary>
        public string privateKeyTime = "gAg1Wv4fcaef5mdeuSKI3iuyFGDW/wgBm0WNNzwZsWirvjGupTew06DLDCY222qmigjgLCibr8VwvxAor461w1iCOcCi0NQlb4WCiHNSefzRbS52mxsfBrJjc7mpdoKloyzfzo7Rx1OM2IxMiWyTZj5/dFoh1rsgaj98co2JuxKV4Y7HznT5WjkbSu9quJ7vbFSXA+eDYaNlxeAZCyfFAN//uT9RgVix7MBzM4XPbjsb88knegayFirGPgOeeQD42ErENdA+r6ZP4iC2+bFD0O7KoDqYrstsMNasKx+NYWTsZTKHD6rba9QCERpo5nLI8T+JA9t2psXnLG1Vi4W8xwE=";
        /// <summary>
        /// 公钥  用于软件解密注册码
        /// </summary>
        public string publicKeyTime = "AwEAAeGOx850+Vo5G0rvarie72xUlwPng2GjZcXgGQsnxQDf/7k/UYFYsezAczOFz247G/PJJ3oGshYqxj4DnnkA+NhKxDXQPq+mT+IgtvmxQ9DuyqA6mK7LbDDWrCsfjWFk7GUyhw+q22vUAhEaaOZyyPE/iQPbdqbF5yxtVYuFvMcB";




        #region 硬件信息读取接口
        ///<summary>
        /// 获取硬盘卷标号
        ///</summary>
        ///<returns></returns>
        public string GetDiskVolumeSerialNumber()
        {
            ManagementClass mc = new ManagementClass("win32_NetworkAdapterConfiguration");
            ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
            disk.Get();
            return disk.GetPropertyValue("VolumeSerialNumber").ToString();
        }

        /// <summary>
        /// 读取硬盘机器码
        /// </summary>
        /// <returns></returns>
        public string Get_HardDisk_Id()
        {
            string HDid = " ";
            using (ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive"))
            {
                ManagementObjectCollection moc1 = cimobject1.GetInstances();
                foreach (ManagementObject mo in moc1)
                {
                    HDid = (string)mo.Properties["Model"].Value;
                    mo.Dispose();
                }
            }
            return HDid.ToString();
        }
        /// <summary>
        /// 读取网卡机器码
        /// </summary>
        /// <returns></returns>
        public string Get_NetworkCard_Id()
        {
            string MoAddress = " ";
            using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
            {
                ManagementObjectCollection moc2 = mc.GetInstances();
                foreach (ManagementObject mo in moc2)
                {
                    if ((bool)mo["IPEnabled"] == true)
                        MoAddress = mo["MacAddress"].ToString();
                    mo.Dispose();
                }
            }
            return MoAddress.ToString();
        }
        ///<summary>
        /// 获取CPU序列号
        ///</summary>
        ///<returns></returns>
        public string GetCpu()
        {
            string strCpu = null;
            ManagementClass myCpu = new ManagementClass("win32_Processor");
            ManagementObjectCollection myCpuCollection = myCpu.GetInstances();
            foreach (ManagementObject myObject in myCpuCollection)
            {
                strCpu = myObject.Properties["Processorid"].Value.ToString();
            }
            return strCpu;
        }
        #endregion


        /// <summary>
        /// 取MD5
        /// </summary>
        /// <param name="myString"></param>
        /// <returns></returns>
        public static string GetMD5(string myString)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;
            for (int i = 0; i < targetData.Length; i++)
            {
                byte2String += targetData[i].ToString("x");
            }
            return byte2String;
        }

        ///<summary>
        /// 获取机器码
        ///</summary>
        ///<returns></returns>
        public string GetMachineCode()
        {
            ///cpu信息
            string cpu = GetCpu();
            //硬盘卷标
            string dist = GetDiskVolumeSerialNumber();
            //网卡信息
            string net = Get_NetworkCard_Id().Replace(":","");
            //MD5信息 
            return GetMD5(cpu + dist + net).ToUpper();
        }

        public bool CheckLicense(String machineCode,
            String regKey,
            String usePeriod,
            String uastUsedDate,
            ref DateTime UsePeriod,
            ref DateTime LastUsedDate,
            ref string msg, 
            String mail = "dhsososo@163.com")
        {
            if (machineCode != RSAHelper.DecryptString(regKey, publicKey))
            {
                msg = $"软件未取得受权，请联系：{mail}";
                return false;
            }
            else
            {
                UsePeriod = DateTime.Parse(RSAHelper.DecryptString(usePeriod, publicKeyTime));
                LastUsedDate = DateTime.Parse(RSAHelper.DecryptString(uastUsedDate, publicKeyTime));
               
                if (UsePeriod >= LastUsedDate)
                {
                    if (DateTime.Now > LastUsedDate)
                    {
                        LastUsedDate = DateTime.Now;
                        msg = "授权正常!";
                        return true;
                    }
                    else
                    {
                        msg = $"软件授权已过期!请保证系统时间正常！请联系：{mail}";
                        return false;
                    }
                }
                else
                {
                    msg = $"软件授权已过期!请联系：{mail}";
                    return false;
                }
            }
        }
        /// <summary>
        /// 检查注册授权
        /// </summary>
        /// <returns></returns>
        public bool CheckLicense(ref string msg, String mail = "dhsososo@163.com")
        {
            try
            {
                String licenseDatPath = AppDomain.CurrentDomain.BaseDirectory + "/license.dat";
                if (!File.Exists(licenseDatPath))
                {
                    String machineCode = GetMachineCode();
                    File.WriteAllText(licenseDatPath, $"{machineCode}///");
                }
                if (File.Exists(licenseDatPath))
                {
                    //1机器码  2注册码   3使用期限  4最后使用日期
                    String[] line = File.ReadAllText(licenseDatPath).Split('/');
                    String machineCode = GetMachineCode();
                    DateTime UsePeriod = new DateTime();
                    DateTime LastUsedDate = new DateTime(); ;
                    
                    if (line[0].Equals(machineCode))
                    {
                        if(CheckLicense(line[0], line[1], line[2], line[3], ref UsePeriod, ref LastUsedDate, ref msg, mail))
                        {

                            line[3] = RSAHelper.EncryptString(LastUsedDate.ToString(), privateKeyTime);
                            File.WriteAllText(licenseDatPath, $"{ machineCode}/{ line[1]}/{ line[2]}/{line[3]}");
                            return true;
                        }
                        else
                        {
                            return false;
                        } 
                    }
                    else
                    {
                        msg = "授权文件与设备不匹配!";
                        return false;
                    }
                }
                msg = "软件异常!";
                return false;
            }
            catch (Exception ex)
            {
                LogHelper.Error("检查注册授权发生异常!",ex);
                msg = $"软件未取得受权，请联系：{mail}";
                return false;
            } 
        }

        /// <summary>
        /// 导入新的注册文件 并检查注册授权
        /// </summary>
        /// <param name="inputFile"></param>
        /// <param name="msg"></param>
        /// <param name="mail"></param>
        /// <returns></returns>
        public bool CheckLicense(String inputFile, ref string msg, String mail = "dhsososo@163.com")
        {
            String licenseDatPath = AppDomain.CurrentDomain.BaseDirectory + "/license.dat";
            String text = File.ReadAllText(inputFile);
            File.WriteAllText (licenseDatPath, text);
            return CheckLicense(ref msg,mail);
        }

        /// <summary>
        /// 获取注册信息
        /// </summary>
        /// <returns></returns>
        public string GetLicense()
        {
            try
            {
                String licenseDatPath = AppDomain.CurrentDomain.BaseDirectory + "/license.dat";
                if (!File.Exists(licenseDatPath))
                {
                    String machineCode = GetMachineCode();
                    File.WriteAllText(licenseDatPath, machineCode);
                    return machineCode;
                }
                else
                {
                    return File.ReadAllText(licenseDatPath);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取注册信息发生异常!", ex);
                return "获取注册信息发生异常!";
            }
        }
    }
}